package com.zheng.process;

import com.zheng.http.Request;
import com.zheng.http.Response;
import com.zheng.mappper.Context;
import com.zheng.mappper.Host;
import com.zheng.mappper.Mapper;
import com.zheng.mappper.Wrapper;
import com.zheng.servlet.HttpServlet;
import com.zheng.util.HttpProtocolUtil;


import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 *  @author: zheng
 *  @Date: 2020-06-23 17:34
 *  @Description:
 */
public class RequestProcessor  extends Thread{

    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket socket,Mapper mapper){
        this.socket=socket;
        this.mapper=mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream=socket.getInputStream();

            //封装Request和Response
            Request request=new Request(inputStream);
            Response response=new Response(socket.getOutputStream());

            String requestUrl=request.getUrl();
            String hostName=request.getHostName();
            List<Host> hostList=mapper.getHostList();
            //验证host是否合法
            if(!isVaild(hostName,hostList)){
                response.outputHtml(HttpProtocolUtil.getHttpHeader404());
                return;
            }else {
                //匹配Servlet
                HashMap pathMap=getUrlObject();
                HttpServlet httpServlet=(HttpServlet) pathMap.get(requestUrl);
                if(httpServlet==null){
                    response.outputHtml(HttpProtocolUtil.getHttpHeader404());
                    return;
                }
                httpServlet.service(request,response);
            }

            socket.close();


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    private   Boolean isVaild(String hostname,List<Host> hostList){
        for(Host host:hostList){
            if (host.getName().equals(hostname)){
                return true;
            }
        }
        return false;
    }

    //把每一层级的path封装到map key作为url
    private  HashMap<String,Object> getUrlObject(){
        List<Host> hostList=mapper.getHostList();
        HashMap hashMap=new HashMap();
        for(Host host:hostList){
            List<Context> contextList=host.getContextList();
            for(Context context:contextList){
                String contextPath=context.getPath();
                List<Wrapper> wrapperList=context.getWrapperList();
                for(Wrapper wrapper:wrapperList){
                    String url=wrapper.getPath();
                    hashMap.put("/"+contextPath+url,wrapper.getServlet());
                }
            }
        }
        return hashMap;
    }


}
